//
//  CZTextView.swift
//  GZWeibo007
//
//  Created by danli on 15/12/27.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class CZTextView: UITextView {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareUI()
      
    }
    
    
    // MARK: 属性
    var placeholderText:String?{
        didSet
        {
            placeholderLabel.text = placeholderText
            placeholderLabel.sizeToFit()
        }
    }
    
    
    func prepareUI()
    {
        addSubview(placeholderLabel)
        
//        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: 5, y: 8))
        
        // 如果这个Label想给其他工程使用,最好少依赖第三方框架
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        // 添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    // 当textView中的文本发生改变时调用
    func textViewTextDidChange()
    {
        placeholderLabel.hidden = hasText()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    // MARK: 懒加载
    lazy var placeholderLabel:UILabel = {
       let label = UILabel()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.darkGrayColor()
        return label
    }()

}
